package de.hauck.rtmidlet.views;

import java.util.Vector;

import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

import de.hauck.rtmidlet.DownloadIBThread;
import de.hauck.rtmidlet.DownloadImageThread;
import de.hauck.rtmidlet.RTMidlet;
import de.hauck.rtmidlet.model.Configuration;
import de.hauck.rtmidlet.model.IBBean;
import de.hauck.rtmidlet.model.IBQueryBean;

public class CanvasIB extends CanvasSuper implements CommandListener, iCanvas {
	// private Displayable _dble;
	private Font f_small;
	public boolean isDownloading = false;
	// private String values = null;
	// private Vector _ibBean;
	private IBQueryBean _ibQueryBean;
	private String reportText;

	private static final int BUY = 0;
	private static final int SELL = 1;
	private static final int TOTAL = 2;
	private int slideType = BUY;

	private Image _image;
	private boolean showChart = false;

	private boolean showMenu = false;
	private PopupMenu pMenu;
	private static String[] menu = { "Today", "Yesterday", "Last Month",
			"This Month" };
	private int menuIndex = 0;
	int stocksOnScreen;
	int maxSlides = 0;
	int entriesPerPage = 0;
	int entries = 0;
	int slide = 1;
	private int startNr = 0;
	private int endNr;

	public CanvasIB() {
		super();
		f_small = Font.getFont(Font.FONT_STATIC_TEXT, Font.STYLE_PLAIN,
				Font.SIZE_SMALL);
		stocksOnScreen = (getHeight() / (2 * f_small.getHeight())) - 1; // -1
		// because
		// of
		// title
		System.out.println("StocksOnScreen: " + stocksOnScreen);
		downloadValues();
		downloadChart();
	}

	protected void paint(Graphics g) {
		super.paint(g);
		pMenu = new PopupMenu(g, Font.getFont(Font.FACE_MONOSPACE,
				Font.STYLE_PLAIN, Font.SIZE_SMALL), getWidth(), getHeight(),
				menu);
		g.setFont(f_small);
		if (showChart) {
			if (_image != null) {
				g.drawImage(_image, getWidth() / 2, (getHeight() / 2)
						- _image.getHeight() / 2, Graphics.TOP
						| Graphics.HCENTER);
			} else
				g.drawString("no chart available", getWidth() / 2,
						getHeight() / 2, Graphics.TOP | Graphics.HCENTER);
		} else {
			// !showChart
			g.setColor(255, 255, 255);
			int ypos = 19;
			int xpos_quantity = 60;
			int xpos_type = 65;
			int xpos_price = (getWidth() / 2) - 15;
			int xpos_amount = getWidth() - 5;

			g.setColor(204, 255, 255);
			g.drawString("Quant.", xpos_quantity, ypos, Graphics.TOP
					| Graphics.RIGHT);
			g.drawString("Type", xpos_type, ypos, Graphics.TOP | Graphics.LEFT);
			g
					.drawString("Rate", xpos_price, ypos, Graphics.TOP
							| Graphics.LEFT);
			g.drawString("Amount", xpos_amount, ypos, Graphics.TOP
					| Graphics.RIGHT);
			ypos += f_small.getHeight() + 2;
			if (null != _ibQueryBean) {
				Vector beans = new Vector();
				if (slideType == BUY) {
					beans = _ibQueryBean.getBuyBeans();
					g.setColor(255, 0, 0);
				} else if (slideType == SELL) {
					beans = _ibQueryBean.getSellBeans();
					g.setColor(0, 255, 0);
				}

				if (null != beans) {
					entries = beans.size() + 1; // +1 because of sums
					maxSlides = (entries / stocksOnScreen);
					if ((entries % stocksOnScreen) > 0)
						maxSlides++;
					System.out.println("maxSlides: " + maxSlides
							+ ", entries: " + entries);
					startNr = slide * stocksOnScreen - stocksOnScreen;
					endNr = Math.min(startNr + stocksOnScreen, beans.size());
					System.out.println("startNr: " + startNr + ", endNr: "
							+ endNr);
					for (int i = startNr; i < endNr; i++) {
						IBBean ib = (IBBean) beans.elementAt(i);
						if (null != ib.getBuySell()) {
							if (slideType == BUY) {
								g.setColor(255, 0, 0);
							} else if (slideType == SELL) {
								g.setColor(0, 255, 0);
							}
							g.drawString("" + ib.getQuantity(), xpos_quantity,
									ypos, Graphics.TOP | Graphics.RIGHT);
							g.drawString("" + ib.getBuySell(), xpos_type, ypos,
									Graphics.TOP | Graphics.LEFT);
							g.drawString(("" + ib.getPrice()).substring(0, Math
									.min(("" + ib.getPrice()).length(), 6)),
									xpos_price, ypos, Graphics.TOP
											| Graphics.LEFT);
							g.drawString(("" + ib.getAmount()).substring(0,
									("" + ib.getAmount()).indexOf(".") + 3),
									xpos_amount, ypos, Graphics.TOP
											| Graphics.RIGHT);
							ypos += f_small.getHeight();
							g.setColor(255, 255, 255);
							g.drawString(ib.getDate() + ", " + ib.getTime(), 5,
									ypos, Graphics.TOP | Graphics.LEFT);
							ypos += f_small.getHeight();
						}
					}

					if (slide == maxSlides) {
						g.setColor(204, 255, 255);
						g.drawLine(5, ypos - 2, getWidth() - 5, ypos - 2);
						ypos += 2;
						
						// buy totals
						g.setColor(255, 0, 0);
						g.drawString("" + _ibQueryBean.getTotalBuyQuantity(),
								xpos_quantity, ypos, Graphics.TOP
										| Graphics.RIGHT);
						g.drawString("BUY", xpos_type, ypos, Graphics.TOP
								| Graphics.LEFT);
						g.drawString(_ibQueryBean.getBuyPriceAsString(),
								xpos_price, ypos, Graphics.TOP | Graphics.LEFT);
						g.drawString("" + _ibQueryBean.getBuyAmountAsString(),
								xpos_amount, ypos, Graphics.TOP
										| Graphics.RIGHT);
						ypos += f_small.getHeight();

						// sell totals
						g.setColor(0, 255, 0);
						g.drawString("" + _ibQueryBean.getTotalSellQuantity(),
								xpos_quantity, ypos, Graphics.TOP
										| Graphics.RIGHT);
						g.drawString("SELL", xpos_type, ypos, Graphics.TOP
								| Graphics.LEFT);
						g.drawString(_ibQueryBean.getSellPriceAsString(),
								xpos_price, ypos, Graphics.TOP | Graphics.LEFT);
						g.drawString("" + _ibQueryBean.getSellAmountAsString(),
								xpos_amount, ypos, Graphics.TOP
										| Graphics.RIGHT);
						ypos += f_small.getHeight();

						// draw totals
						if (_ibQueryBean.getTotalBuyQuantity()
								+ _ibQueryBean.getTotalSellQuantity() >= 0) {
							g.setColor(0, 255, 0);
						} else
							g.setColor(255, 0, 0);

						if (_ibQueryBean.getTotalBuyQuantity()
								+ _ibQueryBean.getTotalSellQuantity() != 0)
							g
									.drawString(
											""
													+ (_ibQueryBean
															.getTotalBuyQuantity() + _ibQueryBean
															.getTotalSellQuantity()),
											xpos_quantity, ypos, Graphics.TOP
													| Graphics.RIGHT);
						if (_ibQueryBean.getTotalBuyAmount()
								+ _ibQueryBean.getTotalSellAmount() > 0)
							g.setColor(0, 255, 0);
						else
							g.setColor(255, 0, 0);
						g
								.drawString(
										("" + (_ibQueryBean.getTotalBuyAmount() + _ibQueryBean
												.getTotalSellAmount()))
												.substring(
														0,
														("" + (_ibQueryBean
																.getTotalBuyAmount() + _ibQueryBean
																.getTotalSellAmount()))
																.indexOf(".") + 3),
										xpos_amount, ypos, Graphics.TOP
												| Graphics.RIGHT);
					}
					// draw totals
				}

			} else {
				// ibQueuryBean==null
				if (null != reportText)
					g.drawString(reportText, getWidth() / 2,
							(getHeight() / 2) + 30, Graphics.TOP
									| Graphics.HCENTER);
				else
					g.drawString("No data available yet", getWidth() / 2,
							30 + getHeight() / 2, Graphics.TOP
									| Graphics.HCENTER);
			}
			if (isDownloading) {
				paintDownloadStatus(g, f_small);
			}
			if (showMenu) {
				pMenu.showMenu((byte) menuIndex, (byte) 0);
			}
			String slideInfo = "";
			switch (slideType) {
			case BUY: {
				slideInfo += "B";
				break;
			}
			case SELL: {
				slideInfo += "S";
				break;
			}
			case TOTAL: {
				slideInfo += "T";
				break;
			}
			}
			if (maxSlides > 1)
				slideInfo += ": " + slide + "/" + maxSlides;
			g.setColor(255, 255, 255);
			g.drawString(slideInfo, 20, 0, Graphics.TOP | Graphics.LEFT);
		}
	}

	protected void downloadValues() {
		isDownloading = true;
		repaint();
		new DownloadIBThread(this, Configuration
				.getIBUrl(Configuration.IB_QUERIES[menuIndex]),
				Configuration.IB_QUERIES[menuIndex]);
	}

	protected void downloadChart() {
		// System.out.println("downloading");
		new DownloadImageThread(
				"http://de.advfn.com/p.php?pid=staticchart&s=FX:EURUSD&p=0&t=23&dm=0&vol=1",
				0, 0, this);
	}

	protected void keyPressed(int keyCode) {
		int action = getGameAction(keyCode);
		if (keyCode == KEY_NUM1) {
			reportText = null;
			downloadValues();
			downloadChart();
		} else if (keyCode == KEY_NUM5 || action == FIRE) {
			if (showMenu) {
				switch (menuIndex) {
				case 0: {
					System.out.println(menuIndex + " Today");
					break;
				}
				case 1: {
					System.out.println(menuIndex + " Yesterday");
					break;
				}
				case 2: {
					System.out.println(menuIndex + " Last Month");
					break;
				}
				case 3: {
					System.out.println(menuIndex + " This Month");
					break;
				}

				}
				downloadValues();
				showMenu = !showMenu;

			} else
				showChart = !showChart;

			repaint();
		} else if (keyCode == -6 || keyCode == -7) {
			RTMidlet.getInstance().showMenu();
		} else if (action == LEFT) {
			if (slideType>0) slideType--; else slideType=2;
			//slideType = Math.abs(slideType - 1) % 3;
			System.out.println("slideType: " + slideType);
			if (slideType==TOTAL) slide=1;
			repaint();
		} else if (action == RIGHT) {
			slideType = (slideType + 1) % 3;
			System.out.println("slideType: " + slideType);
			if (slideType==TOTAL) slide=1;
			repaint();
		} else if (action == DOWN) {
			if (showMenu) {
				menuIndex = (menuIndex + 1) % menu.length;
				System.out.println(menuIndex);

			} else {
				slide++;
				if (slide > maxSlides)
					slide = 1;
			}
			System.out.println("Slide: " + slide + "/" + maxSlides);
			repaint();
		} else if (action == UP) {
			if (showMenu) {
				if (menuIndex > 0)
					menuIndex--;
				else
					menuIndex = menu.length - 1;
				System.out.println(menuIndex);

			} else {
				slide--;
				if (slide == 0)
					slide = maxSlides;
			}
			System.out.println("Slide: " + slide + "/" + maxSlides);
			repaint();
		} else if (keyCode == KEY_NUM0) {
			// 0 = toggle menu
			showMenu = !showMenu;
			repaint();
		} else {
			System.out.println("donnu what to do");
		}
	}

	// public void setValues(String values) {
	// this.values = values;
	// repaint();
	// }

	// public void setBeanVector(Vector bean) {
	// _ibBean = bean;
	// repaint();
	// }

	public void setIBQueryBean(IBQueryBean ibQueryBean) {
		_ibQueryBean = ibQueryBean;
		reportText = null;
		repaint();
	}

	public void setText(String text) {
		reportText = text;
		repaint();
	}

	public void showPic(Image image) {
		// System.out.println("Setting chart");
		_image = image;
	}
}
